#include "spinlock.h"

void spinlock_init(spinlock_t *lock) {
    atomic_store(&lock->locked, 0, RELAXED);
}

void spinlock_lock(spinlock_t *lock) {
    for (;;) {
        // 首先检查锁是否被持有
        while (atomic_load(&lock->locked, RELAXED)) {
            // CPU_RELAX(); // 在实际使用时添加
        }
        // 尝试获取锁
        if (!atomic_exchange(&lock->locked, 1, ACQ_REL)) {
            return;
        }
    }
}

void spinlock_unlock(spinlock_t *lock) {
    atomic_store(&lock->locked, 0, RELEASE);
}

int spinlock_trylock(spinlock_t *lock) {
    return !atomic_exchange(&lock->locked, 1, ACQ_REL);
} 